package com.eqdd.yiqidian.ui.yiqixue;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.eqdd.yiqidian.LearnPhotoActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.GridSpacingItemDecoration;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.AppConstent;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.HttpResultRows;
import com.eqdd.yiqidian.bean.rebuild.LearnPhotoListBean;
import com.eqdd.yiqidian.bean.rebuild.LearnPhotoListBean;
import com.eqdd.yiqidian.bean.rebuild.ZhangPageResultBean;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.utils.BottomSheetUtil;
import com.eqdd.yiqidian.utils.HttpUtil;
import com.eqdd.yiqidian.utils.PicUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.lzy.okrx2.adapter.FlowableBody;
import com.shizhefei.mvc.MVCCoolHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;

/**
 * @author吕志豪 .
 * @date 18-3-7  下午2:51.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

public class LearnPhotoActivity extends BaseActivity {

    private LearnPhotoActivityCustom dataBinding;
    private int pageNum;
    private int menuId;
    private MVCCoolHelper<List<LearnPhotoListBean>> mvcHelper;
    private BottomSheetDialog optionChoose;
    private BottomSheetDialog deleteChoose;
    private int currentPos;
    private LearnPhotoListBean dataItem;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_learn_photo);
        initTopRightText("添加", v -> {
            PicUtil.multi(this, null);
        });
    }

    @Override
    public void initData() {

        menuId = getIntent().getIntExtra(Config.ID, 0);
        String title = getIntent().getStringExtra(Config.TITLE);
        initTopTitleBar(View.VISIBLE, title);
        dataBinding.recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        dataBinding.recyclerView.addItemDecoration(new GridSpacingItemDecoration(3, 15, true));
        SlimAdapterEx<LearnPhotoListBean> slimAdapterEx = SlimAdapterEx.create().register(R.layout.grid_item_photo, new SlimInjector<LearnPhotoListBean>() {
            @Override
            public void onInject(LearnPhotoListBean data, IViewInjector injector) {
                injector.image(R.id.grid_img, data.getImageUrl());
            }
        }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
        ItemClickSupport.addTo(dataBinding.recyclerView).setOnItemClickListener((recyclerView, position, v) -> {
            ArrayList<LocalMedia> localMedia = new ArrayList<>();
            for (int i = 0; i < slimAdapterEx.getData().size(); i++) {
                localMedia.add(PicUtil.localMedia(slimAdapterEx.getDataItem(i).getImageUrl()));
            }
            PicUtil.preview(LearnPhotoActivity.this, position, localMedia);
        }).setOnItemLongClickListener((RecyclerView recyclerView, int position, View v) -> {
            currentPos = position;
            optionChoose = BottomSheetUtil.getBottomSheet(LearnPhotoActivity.this, null, (RecyclerView recyclerView1, int position1, View v1) -> {
                optionChoose.hide();
                switch (position1) {
                    case 0:
                        dataItem = slimAdapterEx.getDataItem(currentPos);
                        HttpUtil.setLearnPhotoMenuBg(LearnPhotoActivity.this, dataItem.getId(), dataItem.getMenuId());
                        break;
                    case 1:
                        deleteChoose = BottomSheetUtil.getBottomSheet(LearnPhotoActivity.this,
                                "确认删除图片?",
                                (RecyclerView recyclerView2, int position2, View v2) -> {
                                    deleteChoose.hide();
                                    dataItem = slimAdapterEx.getDataItem(currentPos);
                                    HttpUtil.deleteLearnPhoto(LearnPhotoActivity.this, dataItem.getId(), dataItem.getMenuId(), () -> {
                                        slimAdapterEx.getData().remove(currentPos);
                                        slimAdapterEx.notifyItemRemoved(currentPos);
                                    });
                                }, "删除");
                        deleteChoose.show();
                }
            }, "设为相册封面", "删除");
            optionChoose.show();
            return true;
        });
        ModelRx2DataSource<LearnPhotoListBean> dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
            @Override
            public Flowable<List> loadSource(int page, Rx2DataSource.DoneActionRegister register) {
                pageNum = page == 1 ? 0 : pageNum;
                return OkGo.<HttpResultRows<LearnPhotoListBean>>post(HttpConfig.BASE_URL + HttpConfig.LEARN_PHOTO_LIST)
                        .params("page", pageNum)
                        .params("menuId", menuId)
                        .converter(new JsonConverter<HttpResultRows<LearnPhotoListBean>>() {
                            @Override
                            public void test() {
                                super.test();
                            }
                        }).adapt(new FlowableBody<>())
                        .flatMap(listResultBean -> {
                            pageNum = listResultBean.getItems().getPage();
                            if (listResultBean.getStatus() == 200) {
                                return Flowable.just(listResultBean.getItems() == null ? new ArrayList<LearnPhotoListBean>() : listResultBean.getItems().getRows());
                            } else {
                                ToastUtil.showShort(listResultBean.getMsg());
                                return Flowable.just(new ArrayList<>());
                            }
                        });
            }
        });
        mvcHelper = new MVCCoolHelper<>(dataBinding.coolRefreshView);
        mvcHelper.setDataSource(dataSource);
        mvcHelper.setAdapter(slimAdapterEx);
        mvcHelper.refresh();
    }

    @Override
    public void setView() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PictureConfig.CHOOSE_REQUEST) {
            List<LocalMedia> localMedias = PictureSelector.obtainMultipleResult(data);
            PostRequest<HttpResult> params = OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.LEARN_ADD_PHOTO)
                    .params("userGuid", AppConstent.user.getGuid())
                    .params("menuId", menuId);
            for (int i = 0; i < localMedias.size(); i++) {
                params.params("file", new File(localMedias.get(i).getCompressPath()));
            }
            params.execute(new DialogCallBack<HttpResult>(LearnPhotoActivity.this) {
                @Override
                public void onSuccess(Response<HttpResult> response) {
                    HttpResult httpResult = response.body();
                    ToastUtil.showShort(httpResult.getMsg());
                    if (httpResult.getStatus() == 200) {
                        mvcHelper.refresh();
                    }
                }
            });
        }
    }
}
